<template>
  <div class="app-container input_width200">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch">
      <el-form-item label="设备名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入设备名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="设备编号" prop="code">
        <el-input
          v-model="queryParams.code"
          placeholder="请输入设备编号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="型号" prop="modelNo">
        <el-input
          v-model="queryParams.modelNo"
          placeholder="请输入型号"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="生产厂家" prop="company">
        <el-input
          v-model="queryParams.company"
          placeholder="请输入生产厂家"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in dict.type.bus_hardware_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
<!--      <el-form-item label="检定时间" prop="checkTime">-->
<!--        <el-date-picker clearable size="small"-->
<!--          v-model="queryParams.checkTime"-->
<!--          type="date"-->
<!--          value-format="yyyy-MM-dd"-->
<!--          placeholder="选择检定时间">-->
<!--        </el-date-picker>-->
<!--      </el-form-item>-->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          :loading="exportLoading"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="deviceList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备名称" align="center" prop="name" />
      <el-table-column label="设备编号" align="center" prop="code" />
      <el-table-column label="型号" align="center" prop="modelNo" />
      <el-table-column label="参数" align="center" prop="property" />
      <el-table-column label="生产厂家" align="center" prop="company" />
      <el-table-column label="数量" align="center" prop="totalQuantity" />
      <el-table-column label="总使用时长" align="center" prop="usageTime" />
      <el-table-column label="使用次数" align="center" prop="usageCount" />
      <el-table-column label="设备图片" align="center" prop="pic" />
      <el-table-column label="启用日期" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="采购人" align="center" prop="purchaser" />
      <el-table-column label="检定时间" align="center" prop="checkTime" width="180">
        <template slot-scope="scope">
          <div>{{ parseTime(scope.row.checkTime, '{y}-{m}-{d}') || '无' }}</div>
          <el-button style="margin-top: 6px" size="mini" type="primary" @click="handleCheckTimeChange(scope.row)">更新日期</el-button>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <div :style="{color: statusColorMap[scope.row.status]}">
            <dict-tag :options="dict.type.bus_hardware_status" :value="scope.row.status"/>
          </div>
          <el-button style="margin-top: 6px" size="mini" type="primary" @click="handleStatusChange(scope.row)">更新状态</el-button>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改平台设备对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="700px" append-to-body class="input_width200">
      <el-form ref="form" :model="form" :rules="rules" label-width="96px" inline>
        <el-form-item label="设备名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入设备名称" />
        </el-form-item>
        <el-form-item label="设备编号" prop="code">
          <el-input v-model="form.code" placeholder="请输入设备编号" />
        </el-form-item>
        <el-form-item label="型号" prop="modelNo">
          <el-input v-model="form.modelNo" placeholder="请输入型号" />
        </el-form-item>
        <el-form-item label="生产厂家" prop="company">
          <el-input v-model="form.company" placeholder="请输入生产厂家" />
        </el-form-item>
        <el-form-item label="数量" prop="totalQuantity">
          <el-input v-model="form.totalQuantity" placeholder="请输入数量" />
        </el-form-item>
        <el-form-item label="总使用时长" prop="usageTime">
          <el-input v-model="form.usageTime" placeholder="请输入总使用时长" />
        </el-form-item>
        <el-form-item label="使用次数" prop="usageCount">
          <el-input v-model="form.usageCount" placeholder="请输入使用次数" />
        </el-form-item>
        <el-form-item label="启用日期" prop="startTime">
          <el-date-picker clearable size="small"
            v-model="form.startTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择启用日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="采购人" prop="purchaser">
          <el-input v-model="form.purchaser" placeholder="请输入采购人" />
        </el-form-item>
        <el-form-item label="检定时间" prop="checkTime">
          <el-date-picker clearable size="small"
                          v-model="form.checkTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="选择检定时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="参数" prop="property" class="width200">
          <el-input v-model="form.property" type="textarea" placeholder="请输入参数" />
        </el-form-item>
        <el-form-item label="备注" prop="remark" class="width200">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option
              v-for="dict in dict.type.bus_hardware_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备图片">
          <imageUpload v-model="form.pic"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 更新状态对话框 -->
    <el-dialog title="状态更新" :visible.sync="statusChangeOpen" width="460px" append-to-body class="input_width200">
      <el-form ref="statusChangeForm" :model="statusChangeForm" :rules="statusChangeRules" label-width="96px" inline>
        <el-form-item label="状态" prop="destStatus">
          <el-select v-model="statusChangeForm.destStatus" placeholder="请选择状态">
            <el-option
              v-for="dict in dict.type.bus_hardware_status"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="更新时间" prop="updateStatusTime">
          <el-date-picker clearable
                          v-model="statusChangeForm.updateStatusTime"
                          type="date"
                          value-format="yyyy-MM-dd HH:mm:ss"
                          placeholder="请选择更新时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="更新人" prop="operator">
          <el-input v-model="statusChangeForm.operator" placeholder="请输入更新人" />
        </el-form-item>
      </el-form>
      <el-divider>更新历史记录</el-divider>
      <el-timeline v-show="updateRecords.length > 0" :reverse="true" style="margin-top: 40px; padding-top: 4px; max-height: 220px;overflow-y: scroll">
        <el-timeline-item
          v-for="(item, index) in updateRecords"
          :key="index"
          type="success"
          :timestamp="item.createTime">
          <el-tag size="mini" :color="statusColorMap[item.destStatus]" effect="dark">
            {{ item.destStatusDes }}
          </el-tag>
          -- {{ item.operator }}
        </el-timeline-item>
      </el-timeline>
      <el-empty v-show="updateRecords.length === 0" :image-size="100" description="暂无更新状态的历史记录"></el-empty>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitStatusChangeForm">确 定</el-button>
        <el-button @click="statusChangeCancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 更新检定时间对话框 -->
    <el-dialog title="检定时间更新" :visible.sync="checkTimeChangeOpen" width="550px" append-to-body class="input_width200">
      <el-form ref="checkTimeChangeForm" :model="checkTimeChangeForm" :rules="checkTimeChangeRules" label-width="96px" inline>
        <el-form-item label="检定日期" prop="checkTime">
          <el-date-picker clearable
                          v-model="checkTimeChangeForm.checkTime"
                          type="date"
                          value-format="yyyy-MM-dd"
                          placeholder="请选择检定日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="检定单位" prop="checkCompany">
          <el-input v-model="checkTimeChangeForm.checkCompany" placeholder="请输入检定单位" />
        </el-form-item>
        <el-form-item label="附件" prop="attachment">
          <FileUpload v-model="checkTimeChangeForm.attachment"></FileUpload>
        </el-form-item>
      </el-form>
      <el-divider>更新历史记录</el-divider>
      <el-timeline v-show="checkTimeRecords.length > 0" :reverse="true" style="margin-top: 40px; padding-top: 4px; max-height: 220px;overflow-y: scroll">
        <el-timeline-item
          v-for="(item, index) in checkTimeRecords"
          :key="index"
          type="success"
          :timestamp="item.createTime">
          单位：{{ item.checkCompany }} -- 日期：{{ item.checkTime }}
        </el-timeline-item>
      </el-timeline>
      <el-empty v-show="checkTimeRecords.length === 0" :image-size="100" description="暂无更新状态的历史记录"></el-empty>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitCheckTimeChangeForm">确 定</el-button>
        <el-button @click="checkTimeChangeCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listDevice, getDevice, delDevice, addDevice, updateDevice, exportDevice } from "@/api/business/device";
import { listHardwareCheckTimeUpdate, updateHardwareCheckTime } from '@/api/business/hardwareCheckTimeUpdate';
import { listHardwareStatusUpdate, updateHardwareStatus } from "@/api/business/hardwareStatusUpdate";
import FileUpload from "@/components/FileUpload";
import Lookup from "../../../utils/business_data_lookup";

export default {
  name: "Device",
  dicts: ['bus_hardware_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 平台设备表格数据
      deviceList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        code: null,
        modelNo: null,
        property: null,
        company: null,
        totalQuantity: null,
        usageTime: null,
        usageCount: null,
        pic: null,
        startTime: null,
        purchaser: null,
        status: null,
        checkTime: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          {
            required: true, message: '请输入名称', trigger: 'blur'
          }
        ],
        code: [
          {
            required: true, message: '请输入编号', trigger: 'blur'
          }
        ],
        modelNo: [
          {
            required: true, message: '请输入型号', trigger: 'blur'
          }
        ],
        status: [
          {
            required: true, message: '请输入状态', trigger: 'blur'
          }
        ]
      },
      // 状态颜色映射
      statusColorMap: {
        0: '#0CB37C',
        1: 'red',
        2: 'orange'
      },
      statusChangeOpen: false,
      statusChangeForm: {},
      statusChangeRules: {
        destStatus: [
          {
            required: true, message: '请输入状态', trigger: 'blur'
          }
        ],
        updateStatusTime: [
          {
            required: true, message: '请选择更新日期', trigger: 'blur'
          }
        ],
        operator: [
          {
            required: true, message: '请输入更新人', trigger: 'blur'
          }
        ],
      },
      checkTimeChangeOpen: false,
      checkTimeChangeForm: {},
      checkTimeChangeRules: {
        checkTime: [
          {
            required: true, message: '请选择检定时间', trigger: 'blur'
          }
        ],
        checkCompany: [
          {
            required: true, message: '请输入检定单位', trigger: 'blur'
          }
        ],
      },
      updateRecords: [],
      checkTimeRecords: []
    };
  },
  created() {
    this.getList();
  },
  components: {
    FileUpload
  },
  methods: {
    /** 查询平台设备列表 */
    getList() {
      this.loading = true;
      listDevice(this.queryParams).then(response => {
        this.deviceList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    statusChangeCancel() {
      this.statusChangeOpen = false;
      this.statusChangeForm = {};
      this.updateRecords = [];
      this.resetForm('statusChangeForm');
    },
    checkTimeChangeCancel() {
      this.checkTimeChangeOpen = false;
      this.checkTimeChangeForm = {};
      this.checkTimeRecords = [];
      this.resetForm('checkTimeChangeForm');
    },
    // 表单重置
    reset() {
      this.form = {
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null,
        deviceId: null,
        name: null,
        code: null,
        modelNo: null,
        property: null,
        company: null,
        totalQuantity: null,
        usageTime: null,
        usageCount: null,
        pic: null,
        startTime: null,
        purchaser: null,
        status: null,
        checkTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.deviceId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加平台设备";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const deviceId = row.deviceId || this.ids
      getDevice(deviceId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改平台设备";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.deviceId != null) {
            updateDevice(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addDevice(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    // 状态更新弹框
    handleStatusChange(row) {
      this.statusChangeCancel();
      this.statusChangeForm.destRecordId = row.deviceId;
      this.statusChangeOpen = true;
      listHardwareStatusUpdate({destRecordId: row.deviceId}).then(response => {
        this.updateRecords = response.rows;
      })
    },
    // 更新状态
    submitStatusChangeForm() {
      this.$refs["statusChangeForm"].validate(valid => {
        if (valid) {
          this.statusChangeForm.updateType = 'DEVICE';
          this.statusChangeForm.destStatusDes = Lookup.getLabel(this.statusChangeForm.destStatus, this.dict.type.bus_hardware_status, 'value', 'label');
          updateHardwareStatus(this.statusChangeForm).then(response => {
            this.msgSuccess("更新状态成功");
            this.statusChangeCancel();
            this.statusChangeOpen = false;
            this.open = false;
            this.getList();
          });
        }
      });
    },
    // 日期更新
    handleCheckTimeChange(row) {
      this.checkTimeChangeCancel();
      this.checkTimeChangeForm.destRecordId = row.deviceId;
      this.checkTimeChangeOpen = true;
      listHardwareCheckTimeUpdate({destRecordId: row.deviceId}).then(response => {
        this.checkTimeRecords = response.rows;
      })
    },
    // 日期更新
    submitCheckTimeChangeForm() {
      this.$refs["checkTimeChangeForm"].validate(valid => {
        if (valid) {
          this.checkTimeChangeForm.updateType = 'DEVICE';
          updateHardwareCheckTime(this.checkTimeChangeForm).then(response => {
            this.msgSuccess("更新状态成功");
            this.checkTimeChangeCancel();
            this.checkTimeChangeOpen = false;
            this.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const deviceIds = row.deviceId || this.ids;
      this.$confirm('是否确认删除平台设备编号为"' + deviceIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delDevice(deviceIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有平台设备数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportDevice(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    }
  }
};
</script>
